package cn.com.woxitech.dev.common;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {

	public static String sendGET(String url) throws Exception {

		String responseBody = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpGet httpget = new HttpGet(url);
			httpget.addHeader("Content-Type", "application/Json; charset=UTF-8");

//			System.out.println("Executing request " + httpget.getRequestLine());

			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}

			};
			responseBody = httpclient.execute(httpget, responseHandler);
			responseBody = new String(responseBody.getBytes("ISO-8859-1"), "UTF-8");
			// System.out.println("----------------------------------------");
			// System.out.println(responseBody);
		} finally {
			httpclient.close();
		}
		return responseBody;
	}
	
	
	public static CloseableHttpClient createSSLInsecureClient() {
        try {
            SSLContext sslContext = new SSLContextBuilder()
                                .loadTrustMaterial(null, new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
					// TODO Auto-generated method stub
					return true;
				}
                    }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return  HttpClients.createDefault();
    }


	public static String sendGETSSL(String url) throws Exception {

		String responseBody = "";
		CloseableHttpClient httpclient = HttpClientUtils.createSSLInsecureClient();
		try {
			HttpGet httpget = new HttpGet(url);
			httpget.addHeader("Content-Type", "application/Json; charset=UTF-8");
//			System.out.println("Executing request " + httpget.getRequestLine());

			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}

			};
			responseBody = httpclient.execute(httpget, responseHandler);
			// System.out.println("----------------------------------------");
			// System.out.println(responseBody);
		} finally {
			httpclient.close();
		}
		return responseBody;
	}
	
	public static String sendPOSTSSL(String url, String body) throws Exception {

		InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(body.getBytes("UTF-8")), -1,
				ContentType.APPLICATION_OCTET_STREAM);
		reqEntity.setChunked(true);

		String responseBody = "";
		CloseableHttpClient httpclient = HttpClientUtils.createSSLInsecureClient();
		try {
			HttpPost httppost = new HttpPost(url);
			httppost.addHeader("Content-Type", "application/Json; charset=UTF-8");
			httppost.setEntity(reqEntity);
//			System.out.println("Executing request " + httppost.getRequestLine());

			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}

			};
			responseBody = httpclient.execute(httppost, responseHandler);
			// System.out.println("----------------------------------------");
			// System.out.println(responseBody);
		} finally {
			httpclient.close();
		}
		return responseBody;
	}

	
	public static String sendPOST(String url, String body) throws Exception {

		InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(body.getBytes("UTF-8")), -1,
				ContentType.APPLICATION_OCTET_STREAM);
		reqEntity.setChunked(true);

		String responseBody = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost(url);
			httppost.addHeader("Content-Type", "application/Json; charset=UTF-8");
			httppost.setEntity(reqEntity);
//			System.out.println("Executing request " + httppost.getRequestLine());

			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}

			};
			responseBody = httpclient.execute(httppost, responseHandler);
			responseBody = new String(responseBody.getBytes("ISO-8859-1"), "UTF-8");
			// System.out.println("----------------------------------------");
			// System.out.println(responseBody);
		} finally {
			httpclient.close();
		}
		return responseBody;
	}

	public static String sendPUT(String url, String body) throws Exception {

		InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(body.getBytes("UTF-8")), -1,
				ContentType.APPLICATION_OCTET_STREAM);
		reqEntity.setChunked(true);

		String responseBody = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPut httppost = new HttpPut(url);
			httppost.addHeader("Content-Type", "application/Json; charset=UTF-8");
			httppost.setEntity(reqEntity);
//			System.out.println("Executing request " + httppost.getRequestLine());

			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}

			};
			responseBody = httpclient.execute(httppost, responseHandler);
			responseBody = new String(responseBody.getBytes("ISO-8859-1"), "UTF-8");
			// System.out.println("----------------------------------------");
			// System.out.println(responseBody);
		} finally {
			httpclient.close();
		}
		return responseBody;
	}

	public static String sendDELETE(String url) throws Exception {
		// TODO Auto-generated method stub
		String responseBody = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpDelete httpdelete = new HttpDelete(url);
			httpdelete.addHeader("Content-Type", "application/Json; charset=UTF-8");

//			System.out.println("Executing request " + httpdelete.getRequestLine());

			// Create a custom response handler
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

				@Override
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity) : null;
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
				}

			};
			responseBody = httpclient.execute(httpdelete, responseHandler);
			responseBody = new String(responseBody.getBytes("ISO-8859-1"), "UTF-8");
			// System.out.println("----------------------------------------");
			// System.out.println(responseBody);
		} finally {
			httpclient.close();
		}
		return responseBody;
	}

}
